<script setup lang="ts">
import { ref, watch, getCurrentInstance, onMounted, computed, onUnmounted } from 'vue'
import { useCoinStore } from '@/store/coin'
import { userStore } from '@/store/user';
import { CoinItem } from "@/interfaces/currency.js";
import { formatNumberWithThousands } from '@/utils/utils';
import { useSettingsStore } from '@/store/theme';
const coinName = useCoinStore()
const instance = getCurrentInstance()
const cctId = ref<string>()
const currencyId = ref<string>()
const props = defineProps(['domInfo'])
const isLoading = ref<boolean>(true)
const height = ref('')
const showType = ref<string>('default')
const sell = ref()

// const coinInfo = computed(() => {
//     isLoading.value = false
//     return useCoinStore().contractKLine[useCoinStore().coinInfo.name + '-USDT']
// })
const coinInfo = ref<CoinItem>({
    src: '',
    percentText: '',
    currencyPair: '',
    amount: 0,
    externalPrice: 0,
    timestamp: 0,
    percent: 0,
    usdAmount: 0,
    cnyAmount: 0,
    hkdAmount: 0,
    eurAmount: 0,
    lowest: 0,
    highest: 0,
    open: 0,
    total: 0,
    checked: false,
    markPrice: 0
})

watch(() => useCoinStore().contractKLine, (val) => {
    if (val) {
        isLoading.value = false
        coinInfo.value = val[useCoinStore().coinInfo.name + '-USDT']
    }
}, {
    deep: true
})
interface OrderItem {
    price: number,
    quantity: number,
    width: number
}
const priceInfo = computed(() => {
    return useCoinStore().getPrice(useCoinStore().coinInfo.name)
})
const sellList = ref<OrderItem[]>([])
const buyList = ref<OrderItem[]>([])
let futures: any
let hycurrencySocket: any
const connectCct = () => {
    if (cctId.value) {
        futures.unsubscribe(cctId.value, `/topic/futures/subscription/${useCoinStore().coinInfo.name}-USDT/0.01`)
    }
    cctId.value = Date.now().toString(36) + Math.floor(Math.random() * 1000).toString(36)
    futures.subscribe(cctId.value, `/topic/futures/subscription/${useCoinStore().coinInfo.name}-USDT/0.01`, (data: any) => {
        const Max = Math.max(...[...data.SELL_ORDERS.slice(0, 40).map((item: any) => item.totalNum), ...data.BUY_ORDERS.slice(0, 40).map((item: any) => item.totalNum)])
        sellList.value = data.SELL_ORDERS.map((item: any) => {
            item.price = item.unitPrice
            item.quantity = item.totalNum
            item.width = item.totalNum / Max * 100
            return item
        }).slice(0, 40).reverse()
        buyList.value = data.BUY_ORDERS.map((item: any) => {
            item.price = item.unitPrice
            item.quantity = item.totalNum
            item.width = item.totalNum / Max * 100
            return item
        }).slice(0, 40)
        sell.value.scrollTo({
            top: 9999,
        })
        isLoading.value = false
    })
}
const connectCurrency = () => {
    if (currencyId.value) {
        hycurrencySocket.unsubscribe(currencyId.value, '/topic/market')
    }
    currencyId.value = Date.now().toString(36) + Math.floor(Math.random() * 1000).toString(36)
    hycurrencySocket.subscribe(currencyId.value, `/topic/market`, (data: CoinItem) => {
        if (data.currencyPair === useCoinStore().coinInfo.name + '-USDT') {
            // coinInfo.value = data
        }
    })
}

const setPrice = (item: any) => {
    if (item.tradingType === "SELL") {
        useCoinStore().setPirce('sell', item.price)
    } else {
        useCoinStore().setPirce('buy', item.price)
    }
}

watch(() => props.domInfo, (v) => {
    const h = (v.height - 165) / 2
    const total = Math.round(h / 24)
    height.value = `${(h / total).toFixed(1)}px`
})
watch(() => coinName.coinInfo.name, (v) => {
    isLoading.value = true
    connectCct()
})
// watch(() => userStore().hycurrencySocket, (val) => {
//     if (val) {
//         if (instance) {
//             hycurrencySocket = instance.appContext.config.globalProperties.$hycurrencySocket
//             if (hycurrencySocket.connected) {
//                 connectCurrency()
//             }
//         }
//     }
// }, { immediate: true })
watch(() => userStore().futures, (val) => {
    if (val) {
        if (instance) {
            futures = instance.appContext.config.globalProperties.$futures
            if (futures.connected) {
                connectCct()
            }
        }
    }
}, { immediate: true })
onMounted(() => {

})
onUnmounted(() => {
    if (futures) {
        futures.unsubscribe(cctId.value, `/topic/subscription/${useCoinStore().coinInfo.name}-USDT/0.01`)
    }
    // if (hycurrencySocket) {
    //     hycurrencySocket.unsubscribe(currencyId.value, '/topic/market')
    // }
})
</script>

<template>
    <div class="px-[16px] h-full overflow-hidden">
        <div
            class="mx-[-16px] px-[16px] py-[10px] text-[14px] flex justify-between items-center border-0  border-b-[1px] border-[#ededed] border-solid dark:border-[#333b47]">
            <div class="h-[20px] dark:text-[#eaebef]">订单薄</div>
            <div class=" cursor-pointer relative z-[2]">
                <svg class="w-[16px] h-full text-gray-400 hover:text-black" viewBox="0 0 24 24"
                    xmlns="http://www.w3.org/2000/svg">
                    <path
                        d="M4.9 10a1.5 1.5 0 011.5 1.5v1A1.5 1.5 0 014.9 14h-1a1.5 1.5 0 01-1.5-1.5v-1A1.5 1.5 0 013.9 10h1zm7.6 0a1.5 1.5 0 011.5 1.5v1a1.5 1.5 0 01-1.5 1.5h-1a1.5 1.5 0 01-1.5-1.5v-1a1.5 1.5 0 011.5-1.5h1zm7.6 0a1.5 1.5 0 011.5 1.5v1a1.5 1.5 0 01-1.5 1.5h-1a1.5 1.5 0 01-1.5-1.5v-1a1.5 1.5 0 011.5-1.5h1z"
                        fill="currentColor"></path>
                </svg>
            </div>
        </div>
        <div class="h-[calc(100%-41px)] py-[10px] box-border overflow-hidden"
            :class="[isLoading ? 'flex justify-center items-center' : '']">
            <div v-show="!isLoading" class="h-[20px] mb-[10px] flex items-center">
                <div class="flex items-center">
                    <span @click="showType = 'default'" class="text-[14px] cursor-pointer">
                        <svg class="icon" aria-hidden="true">
                            <use
                                :xlink:href="showType === 'default' ? (useSettingsStore().greenRise ? '#icon-maimaipan1-copy' : '#icon-maimaipan11-copy') : (useSettingsStore().greenRise ? '#icon-maimaipan2' : '#icon-maimaipan1111-copy')">
                            </use>
                        </svg>
                    </span>
                    <span @click="showType = 'buy'" class="text-[14px] mx-[16px] cursor-pointer">
                        <svg class="icon" aria-hidden="true">
                            <use
                                :xlink:href="showType === 'buy' ? (useSettingsStore().greenRise ? '#icon-maipan1' : '#icon-maimaipan-1-copy') : (useSettingsStore().greenRise ? '#icon-maipan' : '#icon-sell')">
                            </use>
                        </svg>
                    </span>
                    <span @click="showType = 'sell'" class="text-[14px] cursor-pointer">
                        <svg class="icon" aria-hidden="true">
                            <use
                                :xlink:href="showType == 'sell' ? (useSettingsStore().greenRise ? '#icon-maimaipan-1-copy' : '#icon-maipan1') : (useSettingsStore().greenRise ? '#icon-sell' : '#icon-maipan')">
                            </use>
                        </svg>
                    </span>
                </div>
            </div>
            <div v-show="!isLoading" class="h-[20px] flex justify-between items-center text-[12px] mb-[10px]">
                <div class="text-text w-1/3 dark:text-[#707A8A]">价格(USDT)</div>
                <div class="text-text w-1/3 dark:text-[#707A8A] text-right">数量(BTC)</div>
                <div class="text-text w-1/3 dark:text-[#707A8A] text-right">成交额</div>
            </div>
            <div v-show="!isLoading" ref="sell" class="overflow-hidden"
                :style="{ height: showType === 'default' ? 'calc(50% - 53px)' : showType === 'sell' ? 'calc(100% - 106px)' : '0' }">
                <div @click="setPrice(item)" v-for="item, i in sellList" :key="i" :style="{ height }"
                    class="flex justify-between items-center text-[12px] relative overflow-hidden  cursor-pointer hover:border-t-[1px] hover:border-dashed  hover:font-bold hover:border-0 hover:border-t-[#eee] dark:border-t-[#333b47]">
                    <div class="text-fall z-[1] w-1/3">{{ formatNumberWithThousands(item.price) }}</div>
                    <div class="text-black z-[1] dark:text-[#eaebef]  w-1/3 text-right">{{ item.quantity }}</div>
                    <div class="text-black z-[1] dark:text-[#eaebef] w-1/3 text-right">{{ Number(item.price *
                        item.quantity).toFixed(2) }}
                    </div>
                    <div class=" absolute top-0 w-full bg-[rgba(var(--color-fall-rgb),0.1)] h-full z-0 "
                        :style="{ right: `${item.width - 100}%` }">
                    </div>
                </div>
            </div>
            <div v-show="!isLoading" class="flex items-center justify-between my-[10px]">
                <div class="h-[24px] flex items-center">
                    <span class=" text-[20px] font-bold" :class="[coinInfo.percent > 0 ? 'text-rise' : 'text-fall']">{{
                        priceInfo?.unitDecimals ?
                            formatNumberWithThousands(coinInfo.amount.toFixed(priceInfo.unitDecimals))
                            :
                            formatNumberWithThousands(coinInfo.amount) }}</span>
                    <span class="text-text text-[12px] ml-[10px] dark:text-[#707A8A]">${{ priceInfo?.unitDecimals ?
                        formatNumberWithThousands(coinInfo.externalPrice.toFixed(priceInfo.unitDecimals))
                        :
                        formatNumberWithThousands(coinInfo.externalPrice)
                    }}</span>
                </div>
                <div>
                    <span class="iconfont icon-gengduo text-[14px] text-text dark:text-[#707A8A]"></span>
                </div>
            </div>
            <div v-show="!isLoading" class="overflow-hidden"
                :style="{ height: showType === 'default' ? 'calc(50% - 53px)' : showType === 'buy' ? 'calc(100% - 106px)' : '0' }">
                <div @click="setPrice(item)" v-for="item, i in buyList" :key="i" :style="{ height }"
                    class=" flex justify-between items-center text-[12px] relative overflow-hidden  cursor-pointer hover:border-t-[1px] hover:border-dashed  hover:font-bold hover:border-0 hover:border-t-[#eee] dark:border-t-[#333b47]">
                    <div class="text-rise z-[1] w-1/3">{{ formatNumberWithThousands(item.price) }}</div>
                    <div class="text-black dark:text-[#eaebef] z-[1] w-1/3 text-right">{{ item.quantity }}</div>
                    <div class="text-black dark:text-[#eaebef] z-[1] w-1/3 text-right">{{ Number(item.price *
                        item.quantity).toFixed(2) }}
                    </div>
                    <div class=" absolute top-0 w-full bg-[rgba(var(--color-rise-rgb),0.1)]  h-full z-0"
                        :style="{ right: `${item.width - 100}%` }"></div>
                </div>
            </div>
            <Loading v-show="isLoading" />
        </div>
    </div>
</template>

<style scoped></style>